﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using Microsoft.Phone.Controls;

namespace Phone.Framework.Behaviors
{
    public enum ApplicationBarType
    {
        Button,
        MenuItem
    }

    public class ApplicationBarAction : Behavior<PhoneApplicationPage>
    {
        public ApplicationBarType ApplicationBarType { get; set; }

        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
            switch (ApplicationBarType)
            {
                case ApplicationBarType.Button:
                    var button = this.AssociatedObject.ApplicationBar.FindButton(this.ButtonText);
                    button.Click += new EventHandler(button_Click);
                    break;
                case ApplicationBarType.MenuItem:
                    var menuitem = this.AssociatedObject.ApplicationBar.FindMenuItem(this.ButtonText);
                    menuitem.Click += new EventHandler(button_Click);
                    break;
                default:
                    break;
            }
        }

        public void Invoke()
        {
            if (method == null)
                method = TargetObject.GetType().GetMethod(MethodName);
            method.Invoke(TargetObject, null);
        }
        private System.Reflection.MethodInfo method;

        public object TargetObject { get; set; }

        public string MethodName { get; set; }

        void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(TargetObjectName))
            {
                TargetObject = this.AssociatedObject.FindName(TargetObjectName);
            }

            this.AssociatedObject.Loaded -= new RoutedEventHandler(AssociatedObject_Loaded);
        }

        void button_Click(object sender, EventArgs e)
        {
            Invoke();
        }

        public string TargetObjectName { get; set; }

        public string ButtonText { get; set; }
    }
}
